import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import Components from "unplugin-vue-components/vite";
import { VantResolver } from "unplugin-vue-components/resolvers";
import vueJsx from "@vitejs/plugin-vue-jsx"; // 支持jsx语法
import legacy from "@vitejs/plugin-legacy"; // 兼容旧版本浏览器
import { manualChunksPlugin } from "vite-plugin-webpackchunkname"; // 支持自定义chunkname
import viteCompression from "vite-plugin-compression"; // gzip静态资源压缩
import path from "path";
import AutoImport from "unplugin-auto-import/vite"; // 组件中自动导入vue的api
import { createHtmlPlugin } from "vite-plugin-html"; // 压缩html

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  // loadEnv用来加载.env.[mode]文件中的变量
  // loadEnv有三个参数，mode、路径、要加载变量的前缀(默认为VITE_)
  const env = loadEnv(mode, process.cwd());
  console.log("VITE_BASE_PATH:", env.VITE_BASE_PATH);
  console.log("mode:", mode);
  return {
    base: env.VITE_BASE_PATH,
    resolve: {
      alias: {
        // 设置路径别名
        "~": path.resolve(__dirname, "./"),
        "@": path.resolve(__dirname, "./src"),
      },
    },
    plugins: [
      vue(),
      vueJsx(),
      Components({
        resolvers: [VantResolver()],
      }),
      AutoImport({
        // targets to transform
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/, // .vue
        ],
        // global imports to register
        imports: [
          // presets
          "vue",
          "vue-router",
        ],
      }),
      legacy({
        // 为打包后的文件提供传统浏览器兼容性支持
        targets: ["> 1%, last 1 version, ie >= 11"],
        additionalLegacyPolyfills: ["regenerator-runtime/runtime"],
      }),
      manualChunksPlugin(),
      viteCompression({
        verbose: true,
        disable: false,
        threshold: 10240,
        algorithm: "gzip",
        ext: ".gz",
      }),
      createHtmlPlugin({
        minify: true,
        /**
         * 在这里写entry后，你将不需要在`index.html`内添加 script 标签，原有标签需要删除
         * @default src/main.ts
         */
        entry: "/src/main.js",
        /**
         * 如果你想将 `index.html`存放在指定文件夹，可以修改它，否则不需要配置
         * @default index.html
         */
        template: "index.html",
        /**
         * 需要注入 index.html ejs 模版的数据
         */
        inject: {
          data: {
            title: "移动端模板",
            // 解决开发服务钉钉浏览器globalThis is not defined的问题
            injectScript:
              mode === "development"
                ? `<script>
            !(function (t) {
              function e() {
                var e = this || self;
                (e.globalThis = e), delete t.prototype._T_;
              }
              "object" != typeof globalThis &&
                (this
                  ? e()
                  : (t.defineProperty(t.prototype, "_T_", {
                      configurable: !0,
                      get: e,
                    }),
                    _T_));
            })(Object);
            </script>`
                : "",
          },
          // tags: [
          //   {
          //     injectTo: "body-prepend",
          //     tag: "div",
          //     attrs: {
          //       id: "tag",
          //     },
          //   },
          // ],
        },
      }),
    ],
    build: {
      assetsDir: "static",
      minify: "terser",
      terserOptions: {
        compress: {
          drop_console: mode === "production", // 默认为false
          drop_debugger: mode !== "development", // 默认为true
        },
      },
      // sourcemap: mode !== "production",
      rollupOptions: {
        output: {
          //静态资源分类打包
          chunkFileNames: "static/js/[name]-[hash].js",
          entryFileNames: "static/js/[name]-[hash].js",
          assetFileNames: "static/[ext]/[name]-[hash].[ext]",
          // manualChunks(id) {
          //   //静态资源分拆打包
          //   if (id.includes("node_modules")) {
          //     return id
          //       .toString()
          //       .split("node_modules/")[1]
          //       .split("/")[0]
          //       .toString();
          //   }
          // },
        },
      },
    },
    server: {
      port: 8080,
      host: "0.0.0.0", // 将服务暴露在局域网中
      open: true,
      proxy: {
        "/test": {
          target: "https://www.mysite.com",
          changeOrigin: true,
          // configure: (proxy, options) => {
          //   console.log("proxy, options", proxy);
          //   // proxy 是 'http-proxy' 的实例
          // },
          // cookieDomainRewrite: {
          //   "mysite.com": "http://192.168.66.66:8080/",
          // },
        },
      },
    },
  };
});
